const EventEmitter = require('events')
const {desktopCapturer, ipcRenderer} = require('electron')

const peer = new EventEmitter();

const pc = new window.RTCPeerConnection({})

pc.onicecandidate = function (e) {
    // console.log('candidate>>>>>>:', e.candidate)
    if (e.candidate)
        ipcRenderer.send('forward', 'control-candidate', JSON.parse(JSON.stringify(e.candidate)))
}


const dc = pc.createDataChannel('robotchannel');
console.log('dc:::', dc)
setInterval(() => {
    console.log('readyState:', dc.readyState)
}, 2000)
dc.onopen = () => {
    console.log("data channel open");
    peer.on('robot', (type, data) => {
        console.log('dc send robot data:', {type: data})
        dc.send(JSON.stringify({type, data}))
    })
}
dc.onmessage = (event) => {
    console.log('message:', event)
}
dc.onerror = (e) => {
    console.log('error', e)
}

ipcRenderer.on('candidate', async (e, candidate) => {
    console.log('candidate:::', candidate)
    await addIceCandidate(candidate)
})
let candidates = []

async function addIceCandidate(candidate) {
    if (!candidate) {
        return
    }
    candidates.push(candidate)
    if (pc.remoteDescription && pc.remoteDescription.type) {
        for (let i = 0; i < candidates.length; i++)
            await pc.addIceCandidate(new RTCIceCandidate(candidates[i]))
        candidates = []
    }
}

window.addIceCandidate = addIceCandidate

async function createOffer() {
    const offer = await pc.createOffer({
        offerToReceiveAudio: true,
        offerToReceiveVideo: true,
    })
    await pc.setLocalDescription(offer)
    console.log('pc offer:', JSON.stringify(offer))
    return pc.localDescription
}

createOffer().then(offer => {
    ipcRenderer.send('forward', 'offer', {type: offer.type, sdp: offer.sdp})
});

async function setRemote(answer) {
    await pc.setRemoteDescription(answer)
}

ipcRenderer.on('answer', async (e, answer) => {
    await setRemote(answer)
})
//window.setRemote = setRemote;
pc.onaddstream = function (e) {
    console.log('add-steam', e.stream)
    peer.emit('add-stream', e.stream)
}


module.exports = peer
